package com.yanze.schoolinformation.model.http;

import com.google.gson.JsonParseException;
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;

import org.json.JSONException;

import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.text.ParseException;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Created by MrZheng on 2018/4/4.
 */

public abstract class DeforObserver<T> implements Observer<T> {
    private Disposable disposable;

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        disposable = d;
        _onSubscribe(d);
    }

    @Override
    public void onNext(@NonNull T t) {
        _onNext(t);
    }

    @Override
    public void onError(@NonNull Throwable e) {
        String errorMessage;
        if (e instanceof HttpException) {     //   HTTP错误
            errorMessage = "HTTP错误";
        } else if (e instanceof ConnectException
                || e instanceof UnknownHostException) {   //   连接错误
            errorMessage = "网络错误";
        } else if (e instanceof InterruptedIOException) {   //  连接超时
            errorMessage = "链接超时";
        } else if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {   //  解析错误
            errorMessage = "解析错误";
        } else {
            errorMessage = e.getMessage();
        }
        _onError(errorMessage);
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    @Override
    public void onComplete() {
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }

    public abstract void _onSubscribe(Disposable disposable);

    public abstract void _onNext(T entity);

    public abstract void _onError(String msg);
}
